<template>
    <div id="pay" :class="theme">
        <div id="purchased">
            <div class="purchased-top">
                <i class="iconfont icon-fanhui" @click="back()"></i>
                <!--<z-history :type="1"></z-history>-->
                <span>{{text}}</span>
            </div>
        </div>
        <!--支付时间-->
        <div class="pay-time">
            <div class="pay-time-over">支付剩余时间</div>
            <div class="payTime">{{timeOver}}</div>
        </div>
        <!--实付款金额-->
        <div class="pay-money">
            <span>实付款:</span><span class="moneyNum font1">￥{{this.money}}</span>
        </div>
        <!--提示选择付款方式-->
        <div class="pay-hint">请选择以下支付方式：</div>
        <!---选择付款方式-->
        <div class="pay-way">
            <!--微信支付-->
            <div class="pay-wx" @click="wx()" v-if="wxchecked === '1'">
                <div class="pay-way-left">
                    <i class="iconfont icon-weixinzhifu"></i>
                    <span>微信支付</span>
                </div>
                <div class="pay-way-right">
                    <i class="iconfont font1" :class="{'icon-danxuan_xuanzhong':wxchecked  === '1','icon-danxuan_moren':wxchecked  === '2'}"></i>
                </div>
            </div>
            <!--支付宝支付-->
            <div class="pay-zfb" @click="zfb()" v-if="wxchecked === '2'">
                <div class="pay-zfb-left">
                    <i class="iconfont icon-zhifubaozhifu"></i>
                    <span>支付宝支付</span>
                </div>
                <div class="pay-zfb-right">
                    <i class="iconfont font1" :class="{'icon-danxuan_xuanzhong':wxchecked  === '2','icon-danxuan_moren':wxchecked  === '1'}"></i>
                </div>
            </div>
        </div>
        <!--确认支付按钮-->
        <div class="pay-yes btn1" @click="pay()">确认支付￥{{this.money}}</div>
        <div class="payOK"></div>
    </div>
</template>

<script>
    /* 页面用到的js */
    import {userService} from '../../service/userService'
    import pheader from '../../component/common/pre-header.vue'

    //    import wx from 'weixin-js-sdk'
    export default {
        components:{'pheader':pheader},
        data () {
            return {
                text:'支付确认',
                timeOver:'',
                seconds:'',
                start:true,
                money:'0',
                wxchecked:'',
                No:'',
                type1:'',
                token:'',
                checked:false,//支付获取成功openId的回调
                orderNo:'',
                theme:'',
                GWC: {
                    version: '1.1.1',
                    urlParams: {},
                },
            }
        },
        mounted() {
            this.judge();

            this.checked = window.localStorage.getItem('checked');
            if(!this.checked){
                this.checked = false;
            }
            if(this.checked){
                this.orderNo = window.localStorage.getItem('orderNo');
                this.onLoad();
                this.wxpay()
            }else{
                this.type1 = this.$route.params.type;
                window.localStorage.setItem('orderType',this.type1);
                this.orderNo = this.$route.params.orderNo;
                window.localStorage.setItem('orderNo',this.orderNo);
                this.onLoad()
            }
        },
        methods: {
            //渲染
            onLoad:function(){
                //进入支付页面拿到orderNum数据请求
                let that = this;
                let sec;
                userService.getOrders(that.orderNo).then(function(res){
                    if(res.data.success){
                        that.money = that.moneyNo(res.data.datas.amount);
                        let nowDate = new Date().getTime();
                        let overTIme = res.data.datas.expireTime
                        if(parseInt((overTIme - nowDate) / 1000) <= 0){
                            that.seconds = 0;
                            that.time();
                        }else{
                            that.seconds = parseInt((overTIme - nowDate) / 1000);
                            that.time();
                        }
                    }else{
                        //订单错误的操作
//                        alert('初始化订单错误')
                        that.$router.back(-1);
                    }
                });
            },
            //计时器
            time:function(){
                let that = this;
                let s = that.seconds;
                let timeOver = that.timeOver;
                let y,m,d,min,second;
                min = Math.floor(s / 60);
                second = s % 60;
                if (second < 10) { second = '0' + second;}
                if (min < 10) { min = '0' + min;}
                timeOver = min + ':' + second;
                that.timeOver = timeOver;
                let settime = setInterval(function(){
                    s -=1;
                    min = Math.floor(s / 60);
                    second = s % 60;
                    if (second < 10) { second = '0' + second;}
                    if (min < 10) { min = '0' + min;}
                    if(parseInt(min) <= 0 && parseInt(second) <= 0){
                        min = '00';
                        second = '00';
                        clearTimeout(settime)
                        //这里到时间的方法
                        that.$router.push({name:'payment',params:{orderNo:that.orderNo,type:that.type1}})
                    }
                    timeOver = min + ':' + second;
                    that.timeOver = timeOver;
                    return that.timeOver
                },1000);
            },
//            首次加载判断在什么浏览器下打开
            judge:function(){
                let ua = navigator.userAgent.toLowerCase();
                if(ua.match(/MicroMessenger/i)=="micromessenger") {
//                    这里是微信浏览器
                    this.wxchecked = '1'
                } else {
//                    这里不是微信浏览器
                    this.wxchecked = '2'
                }
            },
//            选择微信支付
            wx:function(){
                this.wxchecked = '1'
            },
//            选择支付宝支付
            zfb:function(){
                this.wxchecked = '2'
            },
//            确认支付
            pay:function(){
//                支付宝支付
                let that = this;
                if(that.wxchecked === '2'){
//                    console.log('支付宝支付');
                    that.orderNo = that.$route.params.orderNo;
                    userService.getAlipay({orderNo:that.orderNo,channelId:'ALIPAY_WAP'}).then(function (res) {
//                        console.log(res.data);
                        if(res.data.success){
                            let payOK = document.getElementsByClassName("payOK");
                            payOK[0].innerHTML = res.data.datas.payUrl;
                            document.punchout_form.submit()
                        }else{
//                            alert('订单错误')
                            that.$router.push({name:'payment',params:{orderNo:that.orderNo,type:that.type1}})
                        }
                    })
                }
//                微信支付
                if(that.wxchecked === '1'){
//                    console.log('微信支付');
                    userService.getWxpay({loginType:'WEIXIN',platform:'WXH5',jumpRouter:'wxbaselogin',wxscope:'snsapi_base'}).then(function(res){
                        let code = res.data.code;
                        if(code === 200){
                            //获取静默授权地址成功
                            window.location.href = res.data.datas;
                        }
                    })
                }
            },
            //自动唤醒微信支付
            wxpay:function(){
                let that = this;
                let extra = window.localStorage.getItem('extra');
                let shopId = window.localStorage.getItem('pathId')
                that.orderNo = window.localStorage.getItem('orderNo');
                that.type1 = window.localStorage.getItem('orderType');
                let router = window.document.location.href;

                userService.getConfig({url:router.toString()}).then(function (res) {
                    if(res.data.success){
                        let temp=res.data.datas;
                        wx.config({
                            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                            appId: temp.appId, // 必填，公众号的唯一标识
                            timestamp: temp.wxTimestamp+'', // 必填，生成签名的时间戳
                            nonceStr: temp.wxNoncestr, // 必填，生成签名的随机串
                            signature: temp.wxSignature, // 必填，签名，见附录1
                            jsApiList: [
                                'chooseWXPay'
                            ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                        })
                        userService.getAlipay({orderNo:that.orderNo,channelId:'WX_JSAPI',extra:extra,}).then(function (res) {
                            if(res.data.success){
                                let temps = res.data.datas.payParam;
//                                function onBridgeReady(){
//                                    WeixinJSBridge.invoke(
//                                        'getBrandWCPayRequest', {
//                                            "appId":temp.appId,     //公众号名称，由商户传入
//                                            "timeStamp":temps.timeStamp+'',         //时间戳，自1970年以来的秒数
//                                            "nonceStr":temps.nonceStr, //随机串
//                                            "package":temps.wxPackage,
//                                            "signType":"MD5",         //微信签名方式：
//                                            "paySign":temps.paySign //微信签名
//                                        },
//                                        function(res){
//                                            if(res.err_msg == "get_brand_wcpay_request:ok" ) {}     // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
//                                        }
//                                    );
//                                }
//                                if (typeof WeixinJSBridge == "undefined"){
//                                    if( document.addEventListener ){
//                                        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
//                                    }else if (document.attachEvent){
//                                        document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
//                                        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
//                                    }
//                                }else{
//                                    onBridgeReady();
//                                }

                                wx.ready(function(){
                                    // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
                                    wx.chooseWXPay({
                                        timestamp: temps.timeStamp+'', // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                                        nonceStr: temps.nonceStr, // 支付签名随机串，不长于 32 位
                                        package: temps.wxPackage, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                                        signType:"MD5", // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                                        paySign:temps.paySign, // 支付签名
                                        success: function (res) {
                                            // 支付成功后的回调函数
                                            //分别跳转的路径
                                            //1.知识。2.活动。3.会员。4.商品。5.直播
                                            if(that.type1 == '1'){
                                                let orderId = window.localStorage.getItem('orderId');
                                                window.localStorage.removeItem('checked')
                                                that.$router.push({name:'column',params:{id:orderId}})
//                                        window.location.href = '/shops/'+shopId+'/columnlists/'+orderId
                                            }else if(that.type1 == '2'){
                                                window.localStorage.removeItem('checked')
                                                let orderId = window.localStorage.getItem('orderNo');
                                                that.$router.push({name:'payment',params:{orderNo:orderId,type:that.type1}})
//                                        window.location.href = '/shops/'+shopId+'/payment/'+that.orderNo+'/'+ that.type1
                                            }else if(that.type1 == '3'){
                                                window.localStorage.removeItem('checked')
                                                that.$router.push({name:'vip'})
//                                        window.location.href = '/shops/'+shopId+'/vip'
                                            }else if(that.type1 == '4'){

                                            }else if(that.type1 == '5'){
                                                window.localStorage.removeItem('checked')
                                                let orderId = window.localStorage.getItem('orderId')
                                                that.$router.push({name:'liveDetails',params:{did:orderId}})
//                                        window.location.href = '/shops/'+shopId+'/lives/'+orderId
                                            }else{
                                                window.localStorage.removeItem('checked')
                                            }
                                        },
                                        cancel:function(res){
                                            window.localStorage.removeItem('checked');
                                            if(that.type1 == 3){
                                                that.$router.push({name:'vip'})
//                                        window.location.href = '/shops/'+shopId+'/vip'
                                            }else if(that.type1 == 2){
                                                let orderNo = window.localStorage.getItem('orderNo');
                                                that.$router.push({name:'payment',params:{orderNo:orderNo,type:that.type1}})
//                                        window.location.href = '/shops/'+shopId+'/payment/'+that.orderNo+'/'+ that.type1
                                            }else if (that.type1 == 1){
                                                let orderId = window.localStorage.getItem('orderId');
                                                that.$router.push({name:'column',params:{id:orderId}})
//                                        window.location.href = '/shops/'+shopId+'/columnlists/'+orderId
                                            }else if(that.type1 == 5){
                                                let orderId = window.localStorage.getItem('orderId')
                                                that.$router.push({name:'liveDetails',params:{did:orderId}})
//                                        window.location.href = '/shops/'+shopId+'/lives/'+orderId
                                            }
                                        }
                                    });
                                });

                                wx.error(function(res){
//                            alert('订单错误')
                                    window.localStorage.removeItem('checked')
                                    if(that.type1 == 3){
                                        that.$router.push({name:'vip'})
                                    }else if(that.type1 == 2){
                                        let orderNo = window.localStorage.getItem('orderNo');
                                        that.$router.push({name:'payment',params:{orderNo:orderNo,type:that.type1}})
                                    }else if (that.type1 == 1){
                                        let orderId = window.localStorage.getItem('orderId');
                                        that.$router.push({name:'column',params:{id:orderId}})
                                    }else if(that.type1 == 5){
                                        let orderId = window.localStorage.getItem('orderId')
                                        that.$router.push({name:'liveDetails',params:{did:orderId}})
                                    }
                                    // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
                                });
                            }else{
//                        alert('订单错误');
                                window.localStorage.removeItem('checked')
                                if(that.type1 == 3){
                                    that.$router.push({name:'vip'})
                                }else if(that.type1 == 2){
                                    let orderNo = window.localStorage.getItem('orderNo');
                                    that.$router.push({name:'payment',params:{orderNo:orderNo,type:that.type1}})
                                }else if (that.type1 == 1){
                                    let orderId = window.localStorage.getItem('orderId');
                                    that.$router.push({name:'column',params:{id:orderId}})
                                }else if(that.type1 == 5){
                                    let orderId = window.localStorage.getItem('orderId')
                                    that.$router.push({name:'liveDetails',params:{did:orderId}})
                                }
                            }
                        })
                    }
                })

            },
            //返回按钮
            back:function(){
                let that = this;
                window.localStorage.removeItem('checked')
                if(that.type1 == 3){
                    that.$router.go(-2)
                }else if(that.type1 == 2){
                    that.$router.push({name:'payment',params:{orderNo:that.orderNo,type:that.type1}})
                }else if (that.type1 == 1){
                    that.$router.go(-2)
                }else if(that.type1 == 5){
                    that.$router.go(-2)
                }
            },
            //转换价格
            moneyNo(number){
                let that = this;
                return  isNaN(number) ? 0.00 : parseFloat((number/100).toFixed(2));
            },
        },
    }
</script>

<style lang="less">
    @import url('../../assets/css/theme.less');
    #purchased{
        width:100%;
        z-index:1000;
        .purchased-top{
            text-align: center;
            width:100%;
            height:1.2rem;
            background:#fff;
            box-shadow: inset 0 -1px 0 0 rgba(221,221,221,0.50);
            i{
                float:left;
                font-size:0.5rem;
                line-height:1.2rem;
                margin-left:0.2rem;
                color:#999999;
                display: block;
            }
            span{
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                width: 60%;
                display: inline-block;
                margin-left:-1rem;
                height:1.2rem;
                line-height:1.2rem;
                font-size: 18px;
                color: #333333;
                letter-spacing: 0.3px;
            }
        }
    }
    #pay{
        width:100%;
        position: absolute;
        left:0;
        right:0;
        top:0;
        max-width:450px;
        margin:0 auto;
        bottom:0;
        margin:auto;
        background:#F8F8F8;
        text-align: center;
        .pay-time{
            width:100%;
            height:2.8rem;
            background:#fff;
            margin-top:0.21rem;
            padding:0.53rem;
            box-sizing: border-box;
            .pay-time-over{
                height:0.6rem;
                font-size: 13px;
                color: #666666;
                letter-spacing: 0;
            }
            .payTime{
                line-height:1.1rem;
                font-size: 28px;
                color: #333333;
                font-weight:bold;
            }
        }
        .pay-money{
            width:100%;
            height:1.33rem;
            background:#fff;
            padding:0 0.53rem;
            box-sizing: border-box;
            margin-top:1px;
            span{
                text-align: left;
                line-height:1.33rem;
                float:left;
                font-size: 13px;
                color: #333333;
            }
            .moneyNum{
                float:right;
                font-size: 15px;
                color: #6699FF;
            }
        }
        .pay-hint{
            width:100%;
            height:0.72rem;
            padding:0.32rem 0.53rem 0 0.53rem;
            box-sizing: border-box;
            margin:0.27rem 0;
            text-align: left;
            font-size: 13px;
            color: #999999;
        }
        .pay-way{
            width:100%;
            background:#fff;
            padding:0 0.67rem;
            box-sizing: border-box;
            .pay-wx{
                width:100%;
                height:1.33rem;
                line-height:1.33rem;
                text-align: left;
                .pay-way-left{
                    width:60%;
                    float:left;
                    i{
                        font-size:0.67rem;
                        float:left;
                        margin-right:0.43rem;
                        color:#41B035;
                    }
                    span{
                        font-size: 13px;
                        color: #999999;
                    }
                }
                .pay-way-right{
                    float:right;
                    font-size:0.43rem;
                    color: #DDDDDD;
                    .font1{
                        color:#6699FF;
                    }
                }
            }
            .pay-zfb{
                width:100%;
                height:1.335rem;
                line-height:1.335rem;
                text-align: left;
                .pay-zfb-left{
                    width:60%;
                    float:left;
                    i{
                        font-size:0.67rem;
                        float:left;
                        margin-right:0.43rem;
                        color:#19A0E5;
                    }
                    span{
                        font-size: 13px;
                        color: #999999;
                    }
                }
                .pay-zfb-right{
                    float:right;
                    font-size:0.43rem;
                    color: #DDDDDD;
                    .font1{
                        color:#6699FF;
                    }
                }
            }
        }
        .pay-yes{
            width:90%;
            height:1.2rem;
            background:#6699FF;
            border-radius: 100px;
            margin:0 auto;
            margin-top:1.07rem;
            line-height:1.2rem;
            font-size: 16px;
            color: #FFFFFF;
            letter-spacing: 0;
        }
    }
</style>